package easier.popup.view;

import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;
import androidx.core.content.res.ResourcesCompat;

public class PopupWindowFactory {

    /**
     * 实际显示window
     */
    protected PopupWindow mWindow;

    protected PopupWindowFactory() {

    }

    /**
     * @param view 显示的布局
     */
    public PopupWindowFactory( View view ) {

        mWindow = new PopupWindow( view );
        onWindowCreate( mWindow );
    }

    /**
     * @param anchor 展示
     */
    public void showAsDropDown( View anchor ) {

        showAsDropDown( anchor, 0, 0 );
    }

    public void showAsDropDown( View anchor, int xoff, int yoff ) {

        onWindowBeforeShow( mWindow, anchor );
        mWindow.showAsDropDown( anchor, xoff, yoff );
    }

    public void showAtLocation( View parent, int gravity, int x, int y ) {

        onWindowBeforeShow( mWindow, parent );
        mWindow.showAtLocation( parent, gravity, x, y );
    }

    /**
     * 消失
     */
    public void dismiss() {

        mWindow.dismiss();
    }

    /**
     * @return 是否正在显示
     */
    public boolean isShowing() {

        return mWindow.isShowing();
    }

    /**
     * @param window 创建后回调,用于配置不变的属性
     */
    protected void onWindowCreate( PopupWindow window ) {

        window.setElevation( 20 );
        window.setBackgroundDrawable(
            ResourcesCompat.getDrawable( window.getContentView().getResources(), R.drawable.popup_rect_01, null )
        );

        window.setFocusable( false );
        window.setOutsideTouchable( true );
    }

    /**
     * @param window 显示之前的回调,用于根据锚点配置宽度
     * @param anchor 显示的锚点
     */
    protected void onWindowBeforeShow( PopupWindow window, View anchor ) {

        window.setWidth( anchor.getWidth() );

        int i = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 1, MeasureSpec.AT_MOST );
        View contentView = window.getContentView();
        contentView.measure( i, i );
        int measuredHeight = contentView.getMeasuredHeight();

        int maxHeight = configMaxHeight();
        if ( measuredHeight > maxHeight ) {
            window.setHeight( maxHeight );
        } else {
            window.setHeight( LayoutParams.WRAP_CONTENT );
        }
    }

    /**
     * @return 配置最大宽度 {@link #onWindowBeforeShow(PopupWindow, View)}中比较设置
     */
    protected int configMaxWidth() {

        DisplayMetrics displayMetrics = mWindow.getContentView().getContext().getResources().getDisplayMetrics();
        return (int) (displayMetrics.widthPixels * 0.3f);
    }

    /**
     * @return 配置最大高度 {@link #onWindowBeforeShow(PopupWindow, View)}中比较设置
     */
    protected int configMaxHeight() {

        DisplayMetrics displayMetrics = mWindow.getContentView().getContext().getResources().getDisplayMetrics();
        return (int) (displayMetrics.heightPixels * 0.3f);
    }

}